package com.mdlib.helper.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.hn.plt.config.ClientConfig;
import com.ljlib.core.util.BitmapUtil;
import com.ljlib.help.R;
import com.mdlib.helper.event.ShareEvent;
import com.mdlib.helper.model.entity.ShareEntity;
import com.orhanobut.logger.Logger;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.open.utils.ThreadManager;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.greenrobot.eventbus.EventBus;

/**
 * 作者：HQY on 16/9/13 19:33
 * 邮箱：hqy_xz@126.com
 */
public class ShareUtils {

    private Context mContext;
    private ShareEntity mShareEntity;
    private IWXAPI api;
    public static Tencent mTencent;

    public ShareUtils(Context context, ShareEntity shareEntity) {
        this.mContext = context;
        this.mShareEntity = shareEntity;
        api = WXAPIFactory.createWXAPI(mContext, ClientConfig.WX_APP_ID);
        mTencent = Tencent.createInstance(ClientConfig.QQ_APP_ID, mContext);
    }

    public void WxShare(final String type) {
        if (IsInstall.isWeixinAvilible(mContext)) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    Bitmap bitmap = BitmapUtil.returnBitMap(mShareEntity.getImg_url());
                    if (bitmap != null) {
                        Message message = new Message();
                        if (type.equals("1")) {
                            message.what = 1;
                        } else if (type.equals("2")) {
                            message.what = 2;
                        }
                        message.obj = bitmap;
                        handlers.sendMessage(message);
                    }
                }
            });
            thread.start();
        } else {
            ToastUtil.showToast(mContext.getResources().getString(R.string.generic_wx_install));
        }
    }

    public Handler handlers = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Bitmap bit = (Bitmap) msg.obj;
            Bitmap bits = BitmapUtil.zoomImageToSize(bit, 99, 99);
            WXWebpageObject webpages = new WXWebpageObject();
            webpages.webpageUrl = mShareEntity.getShare_url();
            WXMediaMessage msgs = new WXMediaMessage(webpages);
            msgs.title = mShareEntity.getTitle();
            msgs.description = mShareEntity.getDesc();
            msgs.thumbData = BitmapUtil.bmpToByteArray(bits, true);
            SendMessageToWX.Req reqs = new SendMessageToWX.Req();
            reqs.transaction = buildTransaction("webpage");
            reqs.message = msgs;
            if (msg.what == 2) {
                reqs.scene = SendMessageToWX.Req.WXSceneTimeline;
            } else if (msg.what == 1) {
                reqs.scene = SendMessageToWX.Req.WXSceneSession;
            }
            api.sendReq(reqs);
            super.handleMessage(msg);
        }
    };

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    public void QQShare(String type) {
        if (IsInstall.isQQClientAvailable(mContext)) {
            final Bundle params = new Bundle();
            params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
            params.putString(QQShare.SHARE_TO_QQ_TITLE, mShareEntity.getTitle());
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, mShareEntity.getDesc());
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, mShareEntity.getShare_url());
            params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, mShareEntity.getImg_url());
            params.putString(QQShare.SHARE_TO_QQ_APP_NAME, mContext.getResources().getString(R.string.app_name));
            if (type.equals("1")) {
                params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE);
            } else if (type.equals("2")) {
                params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
            }

            doShareToQQ(params);
        } else {
            Toast.makeText(mContext, mContext.getResources().getString(R.string.generic_qq_install), Toast.LENGTH_SHORT).show();
        }
    }

    private void doShareToQQ(final Bundle params) {
        ThreadManager.getMainHandler().post(new Runnable() {
            @Override
            public void run() {
                mTencent.shareToQQ((Activity) mContext, params, qqShareListener);
            }
        });
    }


    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {
            EventBus.getDefault().post(new ShareEvent(0));
            Logger.e("分享成功!");
        }

        @Override
        public void onComplete(Object response) {
            EventBus.getDefault().post(new ShareEvent(1));
            // TODO Auto-generated method stub
        }

        @Override
        public void onError(UiError e) {
            // TODO Auto-generated method stub
            EventBus.getDefault().post(new ShareEvent(1));
            Logger.e("分享失败");
        }
    };

}
